package com.qf.service.impl;

import com.qf.entity.Order;
import com.qf.entity.OrderExample;
import com.qf.entity.User;
import com.qf.entity.custom.OrderCustom;
import com.qf.entity.UserCouponExample;
import com.qf.mapper.OrderMapper;
import com.qf.mapper.UserCouponMapper;
import com.qf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: ZhangYubin
 * @date: 2020/7/23 21:21
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;


    /**
     * 通过id查询订单
     * @param id 参数userId
     * @return 返回Order的List集合
     */
    @Override
    public List<Order> getOrdersByUserId(int id) {
        if (id != 0){
            return orderMapper.selectShopByUserId(id);
        }else {
            return null;
        }
    }

    /**
     *
     * @param userId 解析token得到的userId
     * @param ordersstatus 解析token得到的ordersstatus
     * @return 返回Order的List集合
     */
    @Override
    public List<Order> getOrdersByStatus(int userId,String ordersstatus) {
//        OrderExample example = new OrderExample();
//        OrderExample.Criteria criteria = example.createCriteria();
//        criteria.andUserIdEqualTo(order.getUserId());
//        criteria.andOrdersstatusEqualTo(order.getOrdersstatus());
//        List<Order> orders = orderMapper.selectByExample(example);
        List<Order> orders = orderMapper.selectOrderByStatus(userId,ordersstatus);
        System.out.println(orders);
        if (orders != null){
            return orders;
        }else {
            return null;
        }
    }

    /**
     * 添加订单
     *
     * @param order 对应order实体类
     * @return 返回1或者-1代表操作成功或者失败
     */
    @Override
    @Transactional
    public int addOrder(Order order) {
        if (order != null) {
            int insert = orderMapper.insertSelective(order);
            if (insert == 1) {
                if (order.getUserId() != null && order.getCouponId() != null) {
                    UserCouponExample userCouponExample = new UserCouponExample();
                    UserCouponExample.Criteria criteria = userCouponExample.createCriteria();
                    criteria.andUserIdEqualTo(order.getUserId());
                    criteria.andCouponIdEqualTo(order.getCouponId());
                    int i = userCouponMapper.deleteByExample(userCouponExample);
                    if (i == 1) {
                        return i;
                    } else {
                        return -1;
                    }
                }
                return insert;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    }
}
